package gogsci

import (
	"fmt"
	"path/filepath"
	"strings"
)

var (
	repoRootPath = "/tmp/gogs"
)

// CI 的环境变量定义.
type Environment map[string]string

const (
	COMMIT_HASH      = "COMMIT_HASH"
	LAST_COMMIT_HASH = "LAST_COMMIT_HASH"

	CHECKOUT_REF = "CHECKOUT_REF"

	COMMIT_MESSAGE = "COMMIT_MESSAGE"
	REPO_NAME      = "REPO_NAME"
	REPO_FULL_NAME = "REPO_FULL_NAME"
	CLONE_URL      = "CLONE_URL"
	SSH_CLONE_URL  = "SSH_CLONE_URL"
	PUSHER_NAME    = "PUSHER_NAME"
	PUSHER_EMAIL   = "PUSHER_EMAIL"
	REPO_ROOT_PATH = "REPO_ROOT_PATH"
	REPO_FULL_PATH = "REPO_FULL_PATH"

	CI_FILE = ".gogsci.yaml"
)

func NewEnvironment(payload *PushPayload) Environment {

	e := make(Environment)

	e[COMMIT_HASH] = payload.After
	e[LAST_COMMIT_HASH] = payload.Before

	if payload.Commits != nil {
		var msg = make([]string, len(payload.Commits))
		for _, c := range payload.Commits {
			msg = append(msg, c.Message)
		}
		e[COMMIT_MESSAGE] = strings.Join(msg, "\n")
	}

	if payload.Repo != nil {
		e[REPO_NAME] = payload.Repo.Name
		e[REPO_FULL_NAME] = payload.Repo.FullName
		e[CLONE_URL] = payload.Repo.CloneURL
		e[SSH_CLONE_URL] = payload.Repo.SSHURL
	}

	if payload.Pusher != nil {
		e[PUSHER_NAME] = payload.Pusher.FullName
		e[PUSHER_EMAIL] = payload.Pusher.Email
	}

	if payload.Sender != nil {
		e[PUSHER_NAME] = payload.Sender.FullName
		e[PUSHER_EMAIL] = payload.Sender.Email
	}

	e[REPO_ROOT_PATH] = repoRootPath
	e[REPO_FULL_PATH] = filepath.Join(repoRootPath, e[REPO_FULL_NAME])
	return e
}

func (e Environment) ENV() []string {
	var res = make([]string, len(e))
	for k, v := range e {
		res = append(res, fmt.Sprintf("%s=%s", k, v))
	}

	return res
}
